import numpy as np
from sklearn.random_projection import GaussianRandomProjection
from sklearn.neighbors import NearestNeighbors

# 1. 数据生成：模拟用户画像
np.random.seed(42)
num_users = 5000    # 模拟5000名用户
original_dim = 100    # 用户画像的原始维度
reduced_dim = 10    # 降维后的维度

# 每名用户的画像向量（例如消费行为、兴趣等）
user_profiles = np.random.rand(num_users, original_dim)
# 模拟目标用户的画像
target_user = np.random.rand(1, original_dim)

# 2. 随机投影降维
# 使用高斯随机投影进行降维
transformer = GaussianRandomProjection(
    n_components=reduced_dim, random_state=42)
user_profiles_reduced = transformer.fit_transform(user_profiles)
target_user_reduced = transformer.transform(target_user)

# 3. 高维空间中的最近邻检索
# 使用原始高维数据查找最相似的用户
nbrs_high = NearestNeighbors(n_neighbors=5,
    metric='euclidean').fit(user_profiles)
distances_high, indices_high = nbrs_high.kneighbors(target_user)

# 4. 降维空间中的最近邻检索
# 使用降维后的数据查找最相似的用户
nbrs_low = NearestNeighbors(n_neighbors=5,
    metric='euclidean').fit(user_profiles_reduced)
distances_low, indices_low = nbrs_low.kneighbors(target_user_reduced)

# 5. 输出结果对比
print("目标用户画像（原始高维）:")
print(target_user[0])

print("\n原始高维空间中最相似的5名用户:")
for i, (index, distance) in enumerate(zip(indices_high[0], distances_high[0])):
    print(f"结果 {i + 1}: 用户ID {index}, 距离 {distance:.4f}")
    
print("\n降维后低维空间中最相似的5名用户:")
for i, (index, distance) in enumerate(zip(indices_low[0], distances_low[0])):
    print(f"结果 {i + 1}: 用户ID {index}, 距离 {distance:.4f}")

# 6. 性能分析
print("\n性能分析:")
print(f"用户画像原始维度: {original_dim}")
print(f"用户画像降维后的维度: {reduced_dim}")
print(f"原始空间最近邻平均距离: {np.mean(distances_high[0]):.4f}")
print(f"降维后空间最近邻平均距离: {np.mean(distances_low[0]):.4f}")